import React, { useState, useEffect, useCallback } from 'react';
import _ from 'lodash';
import { Form, Switch, Radio } from 'antd';
import CustomEChartView from '../../CustomEchart';

export default function demo1() {
  const defaultOption = {
    title: {
      show: true,
      text: '图表标题',
    },
    legend: {
      show: true,
    },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: [15000, 23000, 22400, 21800, 13500, 14700, 26000],
        type: 'line',
      },
    ],
  };

  const [{ isShowTitle, isShowLegend, legendPosition }, setConfig] = useState({
    isShowTitle: false,
    isShowLegend: false,
    legendPosition: 'top',
  });
  const [option, setOption] = useState(defaultOption);

  useEffect(() => {
    setOption((state) => {
      const _state = _.cloneDeep(state);
      _.set(_state, 'title.show', isShowTitle);
      _.set(_state, 'legend.show', isShowLegend);
      _.set(_state, 'legend.position', legendPosition);
      return { ..._state };
    });
  }, [isShowTitle, isShowLegend, legendPosition]);

  const handleToggle = useCallback(
    (type: string) => (cheched: boolean) => {
      setConfig((state) => {
        return {
          ...state,
          [type]: cheched,
        };
      });
    },
    [],
  );

  const handleChangePosition = useCallback((e: any) => {
    setConfig((state) => {
      return {
        ...state,
        legendPosition: e.target.value,
      };
    });
  }, []);

  return (
    <div>
      <Form layout="inline" style={{ marginBottom: 16 }}>
        <Form.Item label="Title">
          <Switch checked={isShowTitle} onChange={handleToggle('isShowTitle')} />
        </Form.Item>
        <Form.Item label="Legend">
          <Switch checked={isShowLegend} onChange={handleToggle('isShowLegend')} />
        </Form.Item>
        <Form.Item label="Legend-Postion">
          <Radio.Group value={legendPosition} onChange={handleChangePosition}>
            <Radio.Button value="top">Top</Radio.Button>
            <Radio.Button value="bottom">Bottom</Radio.Button>
          </Radio.Group>
        </Form.Item>
      </Form>
      <div style={{ height: 400 }}>
        <CustomEChartView option={option} />
      </div>
    </div>
  );
}
